package com.binguo.wxapi.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.*;
import com.binguo.common.util.PriceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class AliPayService {

    private static Logger logger = LoggerFactory.getLogger(AliPayService.class);

	private static String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2lthwwuIXCThUA+34tp63zT825xXpiksmas7g9HTLR2+aBmDIvMxIKrr0MfoaX/fGgaTCvhyaH2rUv2x2CYrGKQv32tCyXSADZB+0tkDfLesYolOr2lxWCn8aUY3gnN3p1Hu9wogKtwvdYQ6JghTNScqyIbPoNwGJ2P6A9AYxgJ6d8UFczFRiz0Sy+uN8Yy1wqTomHyDyE408YVVPF2EuwmLlAqm5u9FGmDBsVJ3Oee4ocE3kKriQVtu5s50F4KpxHdDIW/r7IQwbokakXgkbPmb6cWvCduMKysdVwxuyexD7/Jzu2tGy1cuVc1cNLb/XEwWJmCzgrzpRk64u4ijlQIDAQAB";

	private static String APP_PRIVATE_KEY = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDaW2HDC4hcJOFQD7fi2nrfNPzbnFemKSyZqzuD0dMtHb5oGYMi8zEgquvQx+hpf98aBpMK+HJofatS/bHYJisYpC/fa0LJdIANkH7S2QN8t6xiiU6vaXFYKfxpRjeCc3enUe73CiAq3C91hDomCFM1JyrIhs+g3AYnY/oD0BjGAnp3xQVzMVGLPRLL643xjLXCpOiYfIPITjTxhVU8XYS7CYuUCqbm70UaYMGxUnc557ihwTeQquJBW27mznQXgqnEd0Mhb+vshDBuiRqReCRs+Zvpxa8J24wrKx1XDG7J7EPv8nO7a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oDo1h1ySxegrzaPyu8eH/B4QKBgET/oJIPDC66QuATWqbUOGQ5hsAaV/kMi6zKLyULVjo7lZcPJiVDzu4WztMLoBEvejx+u+RhmlAwqyyNj4x9YgSvf9z3rrkP+Fjymr1Akn/wlY5emkdnADnoaD71OesVnWpoymuS33ck7KPfbE3N4xjqOvAj2w5A0Q4G9oVuM4ZX";


	private static String ALIPAY_PUBLIC_KEY2 = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjLRM3QZ6rzbL635/iWzxnC35FS3YWj0y+vbwn+J8AYWgtJpOl0MI5ArZkMz8o1+UToU5lsnfX2nEZWC/TL2jpkNLL0X+MYKRwjH1BDVUHtDC1XfkOvgoxHy/9X/mV0RRTMZ4VR9lsWFmDMOcLLeLe9S0wzL7IOfq8AeDVuDaxok/G2EFardpWaXQex2SZIMIgyytU/R2Qzy2KwCdoxK72XskKRoF2vdeNTByaYLNNZ06wOfTfWmXu+OyegHDWMkWqrMyAcnJ1A2ZKnQFYpMasGfcqfpvyyT1HXS4QG2YDwBAWpCF/FmpV7/0OJb0OBM9u+i8tXCvKoh9uVmw9WmbSwIDAQAB";


    private static String zfbAppId = "2018041002532274";
    private static String sellerId = "2088031854321595";


    private static String notify_url = "http://binguoai.com:88/index.jsp";

    private static AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
            zfbAppId,APP_PRIVATE_KEY,"json","GBK",ALIPAY_PUBLIC_KEY2,"RSA2");

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 生成支付宝支付链接
     * @param orderNo
     * @param totalAmount
     * @param subject
     * @return 支付宝支付url地址，需要去生成二维码
     */
    public String zfbQrCode(String orderNo, Long totalAmount, String subject){
        //创建API对应的request类
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setNotifyUrl(notify_url);
        request.setBizContent("{" +
                "    \"out_trade_no\":\"" + orderNo + "\"," +
                "    \"seller_id\":\"" + sellerId + "\"," +
                "    \"total_amount\":\"" + PriceUtil.changeF2Y(totalAmount) + "\"," +
                "    \"subject\":\"" + subject + "\"" +
                "    }");
        AlipayTradePrecreateResponse response = null;
        try {
            response = alipayClient.execute(request);
            System.out.print(response.getBody());

            return response.getQrCode();
        } catch (AlipayApiException e) {
            logger.error("ali pay api call exception :", e);
        }
        return null;
    }


    /**
     * 接收支付宝通知处理方法
     * @param request
     */
    public void notify(HttpServletRequest request){
        Map<String, String> map = new HashMap<>(16);
        Enumeration b = request.getParameterNames();
        while (b.hasMoreElements()){
            String na = (String)b.nextElement();
            String va = request.getParameter(na);

            System.out.println("r  " + na + ": " + va);
            map.put(na, va);
        }

        //调用SDK验证签名
        boolean signVerified = false;
        try{
            signVerified = AlipaySignature.rsaCheckV1(map, ALIPAY_PUBLIC_KEY2, "utf-8", "RSA2");
        }catch (AlipayApiException e){
            logger.info("AlipayApiException: " + e);
        }

        if(signVerified){
            System.out.println("Success");
            String trade_no = map.get("out_trade_no");
            String tradeStatus = map.get("trade_status");
            logger.info("Success orderNo: " + trade_no + "trade_status:" + tradeStatus);

            if ("TRADE_SUCCESS".equals(tradeStatus)) {
                //Fixme 订单成功处理方法
            }

        } else {
            logger.info("ali pay failed: {}", map);
        }

    }


    public void getRefund(String orderNo) {
        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + orderNo + "\"" +
                "  }");
        AlipayTradeFastpayRefundQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            logger.info("ali pay call exception: ", e);
        }
        if (response != null && response.isSuccess()) {
            logger.info("退款调用成功:{}", orderNo);
        } else {
            logger.info("退款调用失败:{}", orderNo);
        }

    }

    public void doRefund(String orderNo, Long amount){
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + orderNo + "\"," +
                "\"refund_amount\":\"" + PriceUtil.changeF2Y(amount) + "\"" +
                "  }");
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            logger.info("ali pay refund call exception: ", e);
        }
        if (response != null && response.isSuccess()) {
            logger.info("退款调用成功:{}", orderNo);
        } else {
            logger.info("退款调用失败:{}", orderNo);
        }

    }

    /**
     * 条码支付
     * @param orderNo 订单号
     * @param authCode 支付授权码
     * @param totalAmount 金额 单位分
     * @param subject 标题
     * @return 支付结果：  true支付成功  false 支付失败
     */
    public boolean barCodePay(String orderNo, String authCode, Long totalAmount, String subject){
        //创建API对应的request类
        AlipayTradePayRequest request = new AlipayTradePayRequest();
//        request.setNotifyUrl(notify_url);
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + orderNo + "\"," +
                "\"scene\":\"bar_code\"," +
                "\"auth_code\":\"" + authCode + "\"," +
                "\"subject\":\"" + subject + "\"," +
                "\"timeout_express\":\"2m\"," +
                "\"total_amount\":" + PriceUtil.changeF2Y(totalAmount) + "" +
                "}"); //设置业务参数
        //通过alipayClient调用API，获得对应的response类
        AlipayTradePayResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            logger.info("ali pay bar code pay call exception: ", e);
        }


        if(response!= null && response.isSuccess()){

            int count = 0;
            boolean doWhile = false;

            AlipayTradeQueryRequest orderQueryRequest = new AlipayTradeQueryRequest();
            request.setBizContent("{" +
                    "\"out_trade_no\":\"" + orderNo + "\"" +
                    "}");

            while(true) {
                try {
                    count ++ ;
                    System.out.println(sdf.format(new Date()) + "--订单查询支付状态请求第" + count + "次");

                    AlipayTradeQueryResponse orderQueryResponse = null;
                    try {
                        orderQueryResponse = alipayClient.execute(orderQueryRequest);
                    } catch (AlipayApiException e) {
                        logger.info("ali pay query order status exception: ", e);
                    }

                    if (orderQueryResponse!=null && orderQueryResponse.isSuccess()) {
                        String tradeStatus = orderQueryResponse.getTradeStatus();
                        if ("TRADE_SUCCESS".equals(tradeStatus)) {
                            return true;
                        } else {
                            if (!"WAIT_BUYER_PAY".equals(tradeStatus)) {
                                return false;
                            }
                        }
                    }

                    if (count == 6) {

                        //撤销订单
                        alipayTradeCancel(orderNo);
                        return false;
                    } else {
                        Thread.sleep(5 * 1000); //设置暂停时间 5 秒
                    }
                } catch (InterruptedException e) {
                    logger.info("ali pay loop to query order status exception: ", e);
                }
            }
        } else {
            logger.info("条码支付调用失败:{}", orderNo);
            return false;
        }

    }

    private void alipayTradeQuery(String orderNo){
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + orderNo + "\"" +
                "}");
        AlipayTradeQueryResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            logger.info("ali pay query order status exception: ", e);
        }
        if(response!=null && response.isSuccess()){
            String tradeStatus = response.getTradeStatus();
            if ("TRADE_SUCCESS".equals(tradeStatus)) {
                logger.info("支付查询，支付成功：{}", orderNo);
            }
//            else {
//                if (!"WAIT_BUYER_PAY".equals(tradeStatus)) {
//
//                }
//            }
        } else {
            logger.info("订单取消调用失败:{}", orderNo);
        }

    }

    private boolean alipayTradeCancel(String orderNo) {
        AlipayTradeCancelRequest request = new AlipayTradeCancelRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + orderNo + "\"" +
                "}");
        AlipayTradeCancelResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            logger.info("ali pay cancel order status exception: ", e);
        }
        if (response != null && response.isSuccess()) {
            logger.info("支付订单取消成功：{}", orderNo);
            return true;
        } else {
            logger.info("支付订单取消失败：{}", orderNo);
            return false;
        }
    }

//    public static void main(String[] args) {
//        AliPayService aliPayService = new AliPayService();
//        aliPayService.barCodePay("aaa", "286985000275523723", 100l, "aim");
//
//
//    }

    //支付成功notify_url回调内容
    //r  gmt_create: 2018-06-27 02:13:24
    //r  charset: GBK
    //r  seller_email: jinhuabinguo@sina.com
    //r  subject: aim
    //r  sign: P2e3IY9Wy/TyfG58QyS/FrSzaGJw+iBv/+7ch91aTIUFqVMUalWMFGVJ5vKwaazqnaSPgz6AnAXERYDKszIH7pN3ZVhVESM+qGkwgrdpPVnvHZIjUaCXgQ7lk2ErBpOvkPeBBogHoMstLTuJVU9hMy60gJ+qWt+XFc9+JMX+vQI/ymY+L58GDdUDqdEt5JZ4ZCCFf4PomD+ryNg1grl2JOAx8jAWJpeHW1a9wXjL3eWf7IZNUOcSj3B+74hAFNa3WQjxkE4EpKHDP/ELqmW9lmeCaK9LKzu5LHW6mvdoG3JAC8Xq34AUmw6dV3A2/28lLUYg5b6+sXYAwNYCwjPlrw==
    //r  buyer_id: 2088002469935242
    //r  invoice_amount: 1.00
    //r  notify_id: 48bd5cae8526b973c55059f25019501hut
    //r  fund_bill_list: [{"amount":"1.00","fundChannel":"ALIPAYACCOUNT"}]
    //r  notify_type: trade_status_sync
    //r  trade_status: TRADE_SUCCESS
    //r  receipt_amount: 1.00
    //r  buyer_pay_amount: 1.00
    //r  app_id: 2018041002532274
    //r  sign_type: RSA2
    //r  seller_id: 2088031854321595
    //r  gmt_payment: 2018-06-27 02:13:24
    //r  notify_time: 2018-06-27 02:13:24
    //r  version: 1.0
    //r  out_trade_no: aaa
    //r  total_amount: 1.00
    //r  trade_no: 2018062721001004240541321450
    //r  auth_app_id: 2018041002532274
    //r  buyer_logon_id: 254***@qq.com
    //r  point_amount: 0.00
}
